﻿{{!<Layout}}
{{ViewBag Title='触发器'}}

<div class="ui inverted page dimmer" id="dimmer"><div class="ui loader"></div></div>
<div class="ui small left icon input">
    <input type="text" placeholder="Search Trigger..." id="search-trigger">
    <i class="search icon"></i>
</div>
<span>&nbsp;</span>
<div class="ui small floating dropdown labeled search icon button" id="trigger-group-filter">
    <i class="filter icon"></i>
    <span class="text">Trigger Group</span>
    <div class="menu">
        <div class="header">
            Filter by group
        </div>
        <div class="divider"></div>
        <div class="item" data-show-all="true"><i>All</i></div>
        {{#each ViewBag.Groups}}
        <div class="item">{{.}}</div>
        {{/each}}
    </div>
</div>
<a class="ui right floated primary button" href="{{ActionUrl 'New'}}">
    <i class="plus icon"></i>New
</a>

<div id="msg-panel"></div>

<table class="ui single line table highlight-rows" id="trigger-list">
    <thead>
        <tr>
            <th>Name</th>
            <th>Group</th>
            <th>Schedule</th>
            <th>Start Time</th>
            <th>End Time</th>
            <th>Last Fire Time</th>
            <th>Next Fire Time</th>
            <th>History</th>
        </tr>
    </thead>
    <tbody>
        {{#each Model}}
        {{#if JobHeaderSeparator}}
        <tr class="job-key">
            <td class="job-name">
                <a href="{{ActionUrl 'Edit' 'Jobs' group=JobGroup name=JobName}}">{{JobName}}</a>
            </td>
            <td class="job-group">{{JobGroup}}</td>
            <td colspan="6" style="text-align: right">
                <a href="{{ActionUrl 'PauseJob' @ControllerName}}" class="ui super tiny button btn-pause-all"><i class="pause icon"></i>Pause All</a>
                <a href="{{ActionUrl 'ResumeJob' @ControllerName}}" class="ui super tiny button btn-resume-all"><i class="play icon"></i>Resume All</a>
            </td>
        </tr>
        {{/if}}

        <tr>
            <td class="trigger-name">
                {{#if IsPaused}}<i class="small pause icon" title="Paused"></i>{{/if}}
                <a href="{{ActionUrl 'Edit' @ControllerName group=TriggerGroup name=TriggerName}}" title="{{Description}}">{{TriggerName}}</a>
            </td>
            <td class="trigger-group">{{TriggerGroup}}</td>
            <td class="schedule-desc" data-content="{{ScheduleDescription}}">
                <i class="{{TypeIcon}} icon"></i>{{TypeString}}
            </td>
            <td class="trigger-start">{{nvl StartTime "N / A"}}</td>
            <td class="trigger-end">{{nvl EndTime "N / A"}}</td>
            <td class="trigger-last-fire">{{nvl LastFireTime "N / A"}}</td>
            <td class="trigger-next-fire">{{nvl NextFireTime "N / A"}}</td>
            <td class="trigger-histogram">{{>Histogram History}}</td>
        </tr>
        {{/each}}
    </tbody>
</table>

{{#unless Model}}
{{>EmptyList 'trigger'}}
{{/unless}}

<div style="display:none">
    <div class="ui small vertical menu borderless" id="trigger-context-menu">
        <a class="item menu-edit"><i class="left large blue pencil alternate icon"></i>Edit</a>
        <a class="item menu-copy"><i class="left large clone outline icon"></i>Copy</a>
        <a class="item menu-pause"><i class="left large pause icon" style="color:#e6b800"></i>Pause</a>
        <a class="item menu-resume"><i class="left large play green icon"></i>Resume</a>
        <a class="item menu-delete"><i class="left large red trash alternate outline icon"></i>Delete</a>
    </div>
</div>

<div class="ui mini modal" id="delete-dialog">
    <div class="content">
        <p>Are you sure you want to delete this trigger?</p>
        <p><b class="confirm-item"></b></p>
    </div>
    <div class="actions">
        <div class="ui approve red button">Delete</div>
        <div class="ui cancel button">Cancel</div>
    </div>
</div>

<script>
    initDimmer();

    // search handling

    var fGroup = undefined;
    function applyFilter() {
        const fStr = $('#search-trigger').val().toLowerCase();
        $('#trigger-list > tbody > tr.job-key').hide();
        var lastJobKeyHeader = null;
        $('#trigger-list > tbody > tr').each(function () {
            const $_ = $(this), group = $_.data('trigger-group'), txt = $_.data('fulltext');
            if ($_.hasClass('job-key')) {
                lastJobKeyHeader = $_;
            } else {
                if (txt.indexOf(fStr) !== -1 && (!fGroup || group === fGroup)) { $_.show(); lastJobKeyHeader.show(); } else $_.hide();
            }
        });
    }

    var searchTimer;
    $('#search-trigger').on('input', function (e) {
        window.clearTimeout(searchTimer);
        searchTimer = window.setTimeout(function () {
            searchTimer = null;
            applyFilter();
        }, 100);
    });

    $('#trigger-group-filter').dropdown({
        onChange: function (v, t, elm) {
            if (elm.data('show-all')) fGroup = undefined; else fGroup = t;
            applyFilter();
        }
    });

    // histogram
    initHistogramTooltips($('.histogram > .bar'));

    // schedule tooltip
    $('.schedule-desc').popup({ distanceAway: -12, variation: 'very wide' });

    // prepare table
    const rowIndex = {};
    $('#trigger-list > tbody > tr').each(function () {
        const
            $_ = $(this),
            trgNameElm = $_.find('>.trigger-name'),
            trgName = trgNameElm.find('a').text(),
            trgGroup = $_.find('>.trigger-group').text();

        if (trgName) {
            rowIndex[trgGroup + '.' + trgName] = $_;

            $_.data('fulltext', (trgGroup + '.' + trgName).toLowerCase());
            $_.data('trigger-group', trgGroup);

            trgNameElm.append('<button class="ui icon mini detail button"><i class="dots icon"></i></button>');
        }
    });

    function doAction(url, key) {
        $('#dimmer').dimmer('show');
        $.ajax({
            type: 'POST', url: url,
            data: JSON.stringify(key),
            contentType: 'application/json', cache: false,
            success: function () {
                document.location = '{{ActionUrl ""}}';
            },
            error: function (e) {
                $('#dimmer').dimmer('hide');
                prependErrorMessage(e, $('#msg-panel'));
            }
        });
    }

    // menu handling

    function bindContextMenu(menu, row, triggerName, triggerGroup) {

        const btn = row.find('.detail.button');

        const mnuPause = menu.find('>.menu-pause');
        const mnuResume = menu.find('>.menu-resume');

        if (row.find('i.pause.icon').length > 0) {
            mnuPause.hide();
            mnuResume.show();
        } else {
            mnuResume.hide();
            mnuPause.show();
        }

        mnuPause.attr('href', '{{ActionUrl "Pause"}}');
        mnuResume.attr('href', '{{ActionUrl "Resume"}}');

        const pauseResumeFunc = function () {
            btn.popup('hide');
            doAction($(this).attr('href'), { name: triggerName, group: triggerGroup });
            return false;
        };

        mnuPause.click(pauseResumeFunc);
        mnuResume.click(pauseResumeFunc);

        menu.find('>.menu-edit').attr('href', row.find('>.trigger-name a').attr('href'));
        menu.find('>.menu-copy').attr('href', '{{ActionUrl "Duplicate"}}?group=' + triggerGroup + '&name=' + triggerName);
        menu.find('>.menu-delete').click(function () {
            $('#delete-dialog .confirm-item').text(triggerGroup + '.' + triggerName);
            deleteItem({ name: triggerName, group: triggerGroup }, $('#msg-panel'),
                '{{ActionUrl "Delete"}}', '{{ActionUrl ""}}');
        });

        return menu;
    }

    $('#trigger-list > tbody').on('click', '> tr > td > .detail.button', function () {
        const $button = $(this), $_ = $(this).closest('tr'), triggerName = $_.find('>.trigger-name a').text(), triggerGroup = $_.find('>.trigger-group').text();
        $_.addClass('active-menu'); // to preserve highlighted row
        $button.popup({
            transition: 'slide', position: 'bottom left', variation: 'basic', on: 'click', arrowPixelsFromEdge: 0,
            onCreate: function () { $(this).addClass('context-menu').click(function () { $button.popup('hide'); }); },
            onHide: function () { $_.removeClass('active-menu'); },
            html: bindContextMenu($('#trigger-context-menu').clone(), $_, triggerName, triggerGroup)
        }).off('click').popup('show');
    });

    $('#trigger-list > tbody').on('click', '.btn-pause-all, .btn-resume-all', function () {
        const $_ = $(this).closest('tr'), jobName = $_.find('>.job-name a').text(), jobGroup = $_.find('>.job-group').text();
        doAction($(this).attr('href'), { name: jobName, group: jobGroup });
        return false;
    });

    // lazy loading
    loadAdditionalData(rowIndex, '{{ActionUrl "AdditionalData"}}');

</script>
